package com.universe.demo.springboot.filedemo;

import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

public class FileConstraintValidator implements ConstraintValidator<ValidFile, MultipartFile> {

    private String[] allowedExtensions;
    private long maxSize;

    @Override
    public void initialize(ValidFile constraintAnnotation) {
        this.allowedExtensions = constraintAnnotation.allowedExtensions();
        this.maxSize = constraintAnnotation.maxSize();
    }

    @Override
    public boolean isValid(MultipartFile file, ConstraintValidatorContext context) {
        if (file == null || file.isEmpty()) {
            return false; // 文件不能为空
        }

        // 校验文件大小
        if (file.getSize() > maxSize) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("File size exceeds the maximum limit of " + maxSize + " bytes")
                    .addConstraintViolation();
            return false;
        }

        // 校验文件后缀名
        String filename = file.getOriginalFilename();
        if (filename != null && !isValidExtension(filename)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("File extension is not allowed. Allowed extensions: " + Arrays.toString(allowedExtensions))
                    .addConstraintViolation();
            return false;
        }

        return true;
    }

    private boolean isValidExtension(String filename) {
        String fileExtension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        return Arrays.stream(allowedExtensions)
                     .anyMatch(allowedExtension -> allowedExtension.equalsIgnoreCase(fileExtension));
    }
}
